#!/usr/bin/env python
# encoding: utf-8

"""
    接口部分
    1. 实时行情类
        http://hq.sinajs.cn/list=[市场][股票代码]
        股票名称、今日开盘价、昨日收盘价、当前价格、今日最高价、今日最低价、竞买价、竞卖价、成交股数、成交金额、
        买1手、买1报价、买2手、买2报价、…、买5报价、…、卖5报价、日期、时间
    2. 历史行情类
        http://quotes.money.163.com/service/chddata.html?code=[0上海,1深证][股票代码]&start=[开始日期]&end=[结束日期]&fields=[
            TCLOSE收盘价; HIGH最高价;LOW最低价;TOPEN开盘价;
            LCLOSE前收盘价;CHG涨跌额;PCHG涨跌幅;TURNOVER换手率;
            VOTURNOVER成交量;VATURNOVER成交金额;TCAP总市值;MCAP流通市值
        ]
    3. 输出类(publish，快照)
"""
import requests
from datetime import datetime
from datetime import timedelta
from source.Lib.Tools import StockInfo, Outer


class RealtimeHQ(object):
    def __init__(self):
        self.stockInfo = StockInfo()
        self.out = Outer()

    def flushOnce(self, code):
        market = self.stockInfo.market(code)
        url = f"http://hq.sinajs.cn/list={market}{code}"
        q = requests.get(url)
        if q.status_code == 200:
            content = q.text[q.text.find('"') + 1:q.text.rfind('"')]
            self.out.publish(f"{code}:now")
            self.out.put(code, content)

    def flush(self):
        for code in self.stockInfo.all_stocks():
            self.flushOnce(code)


class HistroyHQ(object):
    def __init__(self):
        self.stockInfo = StockInfo()

    def load_all_stock(self):
        def _etl_csv(_x):
            def _handle_cap(_str):
                if "e+" in _str:
                    _v, _num = _str.split('e+')
                    return str(float(_v) * int(_num))
                else:
                    return _str
            _x = _x.replace('None', '0.0').split(',')
            return [
                _x[1].replace("'", ''),  # 股票代码
                _x[0],  # 日期
                _x[3],  # 收盘价
                _x[4],  # 最高价
                _x[5],  # 最低价
                _x[6],  # 开盘价
                _x[8],  # 涨跌额
                _x[9],  # 涨跌幅
                _x[10],  # 换手率
                _x[11],  # 成交量
                _x[12],  # 成交额
                _handle_cap(_x[13]),  # 总市值
                _handle_cap(_x[14]),  # 流通市值
            ]

        stocks = self.stockInfo.all_stock_day_start()
        now = (datetime.now()-timedelta(days=1)).strftime("%Y-%m-%d")
        for code in self.stockInfo.all_stocks():
            try:
                if code in stocks and stocks[code] == now:
                    continue
                market = self.stockInfo.market(code, isNumber=True)
                if code in stocks:
                    url = f"http://quotes.money.163.com/service/chddata.html?code={market}{code}&start={stocks[code].replace('-','')}"
                else:
                    url = f"http://quotes.money.163.com/service/chddata.html?code={market}{code}"
                q = requests.get(url)
                data = list(map(
                    _etl_csv,
                    filter(
                        lambda x: x.strip(),
                        q.text.split('\r\n')[1:]
                    )
                ))
                if data:
                    print('\t插入', code, ' 数据量:', len(data))
                    self.stockInfo.insert_history(data)
            except (Exception, ):
                import time
                print("Get失败", code)
                time.sleep(1)


if __name__ == '__main__':
    histroy = HistroyHQ()
    histroy.load_all_stock()
